<script setup>
import { ref, nextTick, watch } from "vue";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/auth";
import "jquery-ui-dist/jquery-ui";
import "jquery-ui-dist/jquery-ui.min.css";

const props = defineProps({
    //上传地址
    action:{
        default:"/gateway/jy-system/file/uploadOssFile",
        type:String
    },
    //上传携带的额外参数
    otherParams:{
        default:{},
        type:Object
    },
    //上传请求头
    requestHeaders:{
        default:{
            Authorization: `Bearer ${getToken()}`,
        },
        type:Object
    },
    //上传类型限制
    imgType:{
        default:['image/png','image/jpeg','image/jpg'],
        type:Array
    },
    //上传大小限制
    limitSize:{
        default:5 * 1024 * 1024,
        type:Number
    },
    //是否多传
    multiple:{
        default:false,
        type:Boolean
    },
    //多传下，最大上传数量
    maxImgLength:{
        default:5,
        type:Number
    },
    //是否需要排序
    isSort:{
        default:false,
        type:Boolean
    },
    imageUrlInfo:{
        default:"",
        type:String
    },
    imageListUrlInfo:{
        default:[],
        type:Array
    },
    styles:{
    type:String,
    default:()=> 'width:160px;height:160px;'
  }
})

// ocr等其他的返回值
const ocrValue = ref({})
const baseUrl = import.meta.env.VITE_APP_UPLOADURL;
const UploadLoading = ref(false)

const emit = defineEmits(["backValue",'backOcrValue'])
const imageUrl = ref(props.imageUrlInfo)
const imgList = ref(props.imageListUrlInfo);
const isShow = ref(true);
//上传的图片数量
const uploadImgLength = ref(props.imageListUrlInfo.length);
watch(
  props,
  () => {
    imageUrl.value = props.imageUrlInfo;
    imgList.value = props.imageListUrlInfo || [];
    uploadImgLength.value = imgList.value.length;
  },
  {
    deep: true,
  }
);
//上传成功回调
const handleAvatarSuccess = (response,uploadFile) => {
    if(response.code == 0){
        if(props.multiple){
            imgList.value.push(response.data.fileUrl);
            uploadImgLength.value = imgList.value.length;
        }else{
            imageUrl.value = response.data.fileUrl;
        }
        if(props.otherParams?.type){
            ocrValue.value = response.data || {}
        }
        emitBackValue();
    }else{
        ElMessage.error('上传失败') 
    }
    UploadLoading.value = false
}
const handleFileError = (response)=>{
    ElMessage.error('上传失败') 
    UploadLoading.value = false
}
//上传前条件判断
const beforeAvatarUpload= (file) => {
  
    if(props.multiple){
        if(uploadImgLength.value>props.maxImgLength){
            return false;
        }
        
    }
    const regex = /^(?!.*\.jfif$).*$/;
    const isMatch = regex.test(file.name);
    console.log(isMatch,'isMatch');
    if(!((props.imgType.indexOf(file.type) != -1) && isMatch)){
        ElMessage({
            message: '请上传正确图片格式',
            type: 'warning'
        });
        return false;
    }
    if(file.size > props.limitSize){
        ElMessage({
            message: '图片上传过大',
            type: 'warning'
        });
        return false;
    }
    UploadLoading.value = true
    return true
}
//移除图片
const removeImg = (index)=>{
    if(props.multiple){
        imgList.value.splice(index,1);
        uploadImgLength.value -- ;
    }else{
        imageUrl.value = "";
    }
    emitBackValue();
}
const emitBackValue = ()=>{
    if(props.multiple){
        emit("backValue",imgList.value)
    }else{
        emit("backValue",imageUrl.value)
    }
    if(props.otherParams?.type){
        emit('backOcrValue',ocrValue.value)
    }
}
//开始绘制排序内容
const initDraw = () => {
  if (!props.isSort) return;
  nextTick(() => {
    $(function () {
      $("#sortable").sortable({
        cursor: "move",
        cancel: ".avatar-area",
        opacity: 0.9, //拖动时，透明度为0.6
        placeholder: "img-div-hold",
        update: function (event, ui) {
          //更新排序之后
          var picids = $(this).sortable("toArray");

          picids = picids.filter((value) => {
            return (value ?? "") !== "";
          });
          imgList.value = [];
          isShow.value = false;
          setTimeout(() => {
            isShow.value = true;
            imgList.value = picids;
            emitBackValue();
          }, 300);
        },
      });
      $("#sortable").disableSelection();
    });
  });
};
initDraw();
</script>
<template>
  <div class="" >
    <transition name="fade">
        <div v-show="isShow" class="h100 w100" >
            <div class="img-area  h100 w100" id="sortable">
                <div :style="styles" class="avatar-area" v-if="(!multiple && !imageUrl) || (multiple && (imgList.length < maxImgLength))">
                    <el-upload
                    class="avatar-uploader"
                    v-loading="UploadLoading"
                    :action="baseUrl + action"
                    :data="otherParams"
                    :headers="requestHeaders"
                    :show-file-list="false"
                    :multiple="multiple"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :on-error="handleFileError"
                    >
                        <img src="@/assets/images/plus-img.png" alt="" style="width: 40px;height: 40px;">
                        <template #tip>
                            <slot name="tips"></slot>
                        </template>
                    </el-upload>   
                </div>
                <template v-if="multiple && imgList.length>0">
                    <div :style="styles" class="img" v-for="(item,index) in imgList" :key="index" :id="item">

                        <el-image
                        style="width: 100%; height: 100%"
                        :src="item"
                        :zoom-rate="1.2"
                        :preview-src-list="[item]"
                        :initial-index="4"
                        fit="fill"
                        :preview-teleported="true"
                        />
                        <div class="close">
                            <img src="@/assets/images/black_guanbi.png" alt="" @click.stop="removeImg(index)">
                        </div>
                    </div>
                </template>

            </div>
        </div>
    </transition>
    <div :style="styles" class="img" v-if="imageUrl && !multiple">
      <el-image
        style="width: 100%; height: 100%"
        :src="imageUrl"
        :zoom-rate="1.2"
        :preview-src-list="[imageUrl]"
        :initial-index="4"
        fit="fill"
        :preview-teleported="true"
      />
      <div class="close">
        <img
          src="@/assets/images/black_guanbi.png"
          alt=""
          @click.stop="removeImg"
        />
      </div>
    </div>
  </div>
</template>
<style scoped lang="less">
@globalWidth: 160px;
@globalHeight: 160px;
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  display: block;
}
.img-area {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 16px;
  // margin-left: 16px;
  .img {
    // margin-right: 16px;
    // margin-bottom: 20px;
  }
  .avatar-area {
    // margin-right: 16px;
  }
}

.avatar-area {
  //   width: @globalWidth;
  //   height: @globalHeight;
  width: 100%;
  height: 100%;
  position: relative;
  // margin-right: 16px;
  // margin-bottom: 20px;
}
.img {
  //   width: @globalWidth;
  //   height: @globalHeight;
  width: 100%;
  height: 100%;
  position: relative;
  border: 1px solid #dcdfe6ff;
  border-radius: 4px;
  overflow: hidden;
  :deep(.el-image) {
    border: none;

    img {
      border-radius: 4px;
    }
  }

  .close {
    position: absolute;
    right: 7px;
    top: 1px;
    img {
      width: 14px;
      height: 14px;
      cursor: pointer;
      &:hover {
        transform: scale(1.3);
      }
    }
  }
}
</style>

<style lang="less">
@globalWidth: 160px;
@globalHeight: 160px;
.avatar-uploader {
  width: 100%;
  height: 100%;

}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background: #f3f3f3;
  //   width: @globalWidth;
  //   height: @globalHeight;
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  //   width: @globalWidth;
  //   height: @globalHeight;
  width: 100%;
  height: 100%;
  text-align: center;
}
.img-div-hold {
  position: relative;
  margin-right: 16px;
  //   width: @globalWidth;
  //   height: @globalHeight;
  width: 100%;
  height: 100%;
  background: #f3f3f3;
  margin-left: 16px;
  margin-bottom: 20px;
  border: 1px dashed var(--el-border-color);
}
</style>
